#include "RenderModelLocal.h"
#include "PVRTglesExt.h"
#include "tr_local.h"

RenderModelStatic::RenderModelStatic()
{
    glBufVtxIds = NULL;
    glBufIdxIds = NULL;

    purged = true;
}

RenderModelStatic::~RenderModelStatic()
{
    if( glBufVtxIds ) {
        glDeleteBuffers( surfaces.size(), glBufVtxIds );
        delete [] glBufVtxIds;
    }
    if( glBufIdxIds ) {
        glDeleteBuffers( surfaces.size(), glBufIdxIds );
        delete [] glBufIdxIds;
    }

    ModelSurfaceList::iterator it = surfaces.begin();
    for( ; it != surfaces.end(); ++it ) {
        FreeSurfaceTriangles( it->geometry );
    }
}

void RenderModelStatic::InitFromFile( const char* fileName )
{
    // must be empty
}

const char* RenderModelStatic::GetName() const
{
    return name;
}

void RenderModelStatic::TouchData()
{

}

bool RenderModelStatic::IsLoaded() const
{
    return !purged;
}

void RenderModelStatic::LoadModel()
{
    // must be empty
}

void RenderModelStatic::PurgeModel()
{
    int i;
    modelSurface_t* surf;

    for( i=0; i<surfaces.size(); ++i ) {
        surf = &surfaces[i];

        if( surf->geometry ) {
            R_FreeStaticTriSurf( surf->geometry );
        }
    }

    surfaces.clear();

    purged = true;
}

void RenderModelStatic::AddSurface( modelSurface_t& surface )
{
    surfaces.append( surface );
}

void RenderModelStatic::FinishSurfaces()
{
    glBufVtxIds = new unsigned int[surfaces.size()];
    glBufIdxIds = new unsigned int[surfaces.size()];

    glGenBuffers( surfaces.size(), glBufVtxIds );
    glGenBuffers( surfaces.size(), glBufIdxIds );

    modelSurface_t* modelSurf = NULL;

    for( int i=0; i<surfaces.size(); ++i ) {
        modelSurf = &surfaces[i];
        modelSurf->id = i;

        glBindBuffer(GL_ARRAY_BUFFER, glBufVtxIds[i]);
        glBufferData(GL_ARRAY_BUFFER, modelSurf->geometry->numVerts*sizeof(DrawVert), &modelSurf->geometry->verts[0], GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, glBufIdxIds[i]);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, modelSurf->geometry->numIndexes*sizeof(index_t), &modelSurf->geometry->indexes[0], GL_STATIC_DRAW);
    }
}

int RenderModelStatic::NumSurfaces() const
{
    return surfaces.size();
}

modelSurface_t* RenderModelStatic::GetSurface( int index )
{
    return &surfaces[index];
}

srfTriangles_t* RenderModelStatic::AllocSurfaceTriangles( int numVerts, int numIndexes )
{
    srfTriangles_t* tri = R_AllocStaticTriSurf();
    R_AllocStaticTriSurfVerts( tri, numVerts );
    R_AllocStaticTriSurfIndexes( tri, numIndexes );
    tri->numVerts = numVerts;
    tri->numIndexes = numIndexes;
    return tri;
}

void RenderModelStatic::FreeSurfaceTriangles( srfTriangles_t* srf )
{
    R_FreeStaticTriSurf( srf );
}

inf::Bounds RenderModelStatic::Bounds( const renderEntity_s* ent /*= NULL */ )
{
    return bounding;
}
